/*
   Command to be run inside $PROMPT_COMMAND, like so:
     export PROMPT_COMMAND="fc -ln 0 |bashrecord"

   Because bash blocks on the completion of this command, it needs to run
   quickly and silently.
*/

package main

import (
	"echolalia"
	"flag"
	"io/ioutil"
	"log"
	"net/rpc"
	"os"
	"os/user"
	"strings"
	"time"
)

var dest = flag.String("dest", "localhost:11121", "echolalia local service address")

func main() {
	// TODO: set logging to go to a file instead of stderr.

	cmd, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Fatal(err)
	}

	client, err := rpc.DialHTTP("tcp", *dest)
	if err != nil {
		log.Fatal(err)
	}

	hostname, _ := os.Hostname()
	user, _ := user.Current()
	args := &echolalia.Command{
		time.Now(),
		strings.TrimSpace(string(cmd)),
		os.Getppid(),
		os.Getenv("PWD"),
		*user,
		hostname,
	}
	var reply int
	err = client.Call("LocalProtocol.RecordCommand", args, &reply)
	if err != nil {
		log.Fatal(err)
	}
}
